// pages/login/login.js
Page({

  data: {
    showBind: false,
    openid: null,
  },

  onLoad(options) {
    var that = this;
    wx.login({
      success(res) {
        console.log(res)
        if (res.code) {
          that.loginNet(res.code)
        } else {
          console.log('登录失败！' + res.errMsg)
          wx.showToast({
            title: "微信登录失败",
            icon:"error",
          })
        }
      }
    })
  },
  loginNet(code){
    var that = this;
    wx.request({
      url: 'https://api.dianshiyexiao.com/weapp/login',
      method: 'POST',
      data: {
        code: code,
      },
      success(res) {
        //var data = JSON.parse(res.data);
        console.log(res.data)
        var net_data = res.data.data;
        //console.log(res.data.status)
        if(!net_data){
          wx.showToast({
            title: res.data.message,
            icon:"error",
          })
        }
        if(net_data.status){
          wx.showToast({
            title: net_data.msg,
            icon:"error",
          })
          if(net_data.status == 400){
            that.setData({
              openid: net_data.openid,
              showBind: true,
            })
          }
        }
        if(net_data.token.token){
          //正常
          that.close(net_data.token.token)
        }
      },
      fail(error) {
        wx.showToast({
          title: error,
          icon:"error",
        })
      },
    })
  },
  getPhoneNumber(e) {
    var that = this;
    console.log(e)
    console.log(e.detail.code) // 动态令牌
    console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
    console.log(e.detail.errno) // 错误码（失败时返回）
    if (e.detail.code) {
      wx.request({
        url: 'https://api.dianshiyexiao.com/weapp/bindPhone',
        method: 'POST',
        data: {
          code: e.detail.code, //手机号的code
          openid: that.data.openid
        },
        success(res) {
          console.log(res)
          var token = res.data.data.token.token;
          console.log(token)
          that.close(token)
        },
        fail(error) {
          console.log(error)
        },
      })
    }
  },
  close(token) {
    wx.showToast({
      title: '登陆成功',
      icon: "none",
    })
    wx.setStorageSync('token', token)
    this.shauxin();
    wx.navigateBack();
  },
  shauxin() {
    var page = getCurrentPages();
    let prevPage = page[page.length - 2];
    if (prevPage == undefined || prevPage == null) return;
    console.log(prevPage)
    prevPage.getNet(); // 刷新数据
  }
})